package com.ruoyi.project.app.util;

import com.ruoyi.common.utils.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PhoneUtils {
    private static final PhoneUtils instance = new PhoneUtils();

    private PhoneUtils() {
    }

    public static PhoneUtils getInstance() {
        return instance;
    }

    /**
     * 正则匹配验证手机号
     *
     * @param phone 手机号
     * @return 是否是正确手机号
     */
    public boolean isMatcherPhone(String phone) {
        Pattern p = Pattern.compile("^((17[0-9])|(14[0-9])|(13[0-9])|(15[0-9])|(18[0-9]))\\d{8}$");
        Matcher m = p.matcher(phone);
        return m.matches();
    }


    public static void checkCode(String uid, String phone, String code, HttpServletRequest request, String type) {

        if(StringUtils.isBlank(phone)){
            throw new IllegalArgumentException("手机号不能为空");
        }

        if(StringUtils.isBlank(code)){
            throw new IllegalArgumentException("验证码不能为空");
        }

        if(StringUtils.isBlank(code)){
            throw new IllegalArgumentException("验证码不能为空");
        }

        //验证验证码是否有效
        Object attribute = request.getSession().getServletContext().getAttribute(phone);
        if (attribute instanceof CodeEntity) {
            CodeEntity codeEntity = (CodeEntity) attribute;
            //验证验证码是否存在
            if (!StringUtils.equals(codeEntity.getType(),type)) {
                throw new IllegalArgumentException("验证码错误");
            }
            //验证验证码是否一致
            if (!StringUtils.equals(codeEntity.getCode(), code)) {
                throw new IllegalArgumentException("验证码错误");
            }

            //验证时间是否有效3分钟有效
            if ((System.currentTimeMillis() - codeEntity.getDate().getTime()) > 180000) {
                throw new IllegalArgumentException("验证码失效，请重新发送");
            }
//            System.out.println("验证码正确了。。。。。");
        } else {
            throw new IllegalArgumentException("验证码错误");
        }
    }
}
